<?php

namespace App\Core\Utils\Oauth\WechatSdk;

use App\Core\Utils\TwHelper\CommFunction;
use Illuminate\Support\Facades\App;

class WechatConnect
{


    /**
     * 微信相关文档
     * https://open.weixin.qq.com/cgi-bin/showdocument?action=dir_list&t=resource/res_list&verify=1&id=open1419316505&token=&lang=zh_CNs
     **/

    const APP_ID = 'wx676f3bff77fcbd90';
    const APP_SECRET = '5645b7a39c278eb8b161c4a680c1826a';
    const OAUTH_STATE_KEY = "tongwei:oauth:state";

    //获取code的url
    //https://open.weixin.qq.com/connect/qrconnect?appid=APPID&redirect_uri=REDIRECT_URI&response_type=code&scope=SCOPE&state=STATE#wechat_redirect
    const WECHAT_GET_CODE_URL = 'https://open.weixin.qq.com/connect/qrconnect?appid=';
    //获取access_token的url
    //https://api.weixin.qq.com/sns/oauth2/access_token?appid=APPID&secret=SECRET&code=CODE&grant_type=authorization_code
    const WECHAT_GET_ACCESS_TOKEN_URL = 'https://api.weixin.qq.com/sns/oauth2/access_token?appid=';
    //获取userinfo的url
    const WECHAT_GET_USERINFO_URL = 'https://api.weixin.qq.com/sns/userinfo?access_token=';

    //正式的微信回调地址
    const REDIRECT_URI_MASTER = 'http://www.tongwei.cn/oauth/wechatcallback';
    //测试的微信回调地址
    const REDIRECT_URI_DEV = 'http://www.tongwei.cn/oauth/wechatcallback';

    public static function getState()
    {
        return CommFunction::makeRandomKey();
    }

    public static function getRedirectUri()
    {
        if (App::environment('master')) {
            return self::REDIRECT_URI_MASTER;
        } elseif (App::environment('dev')) {
            return self::REDIRECT_URI_DEV;
        }
    }

    /**
     * 获取授权code的url
     */
    public static function getCodeUrl()
    {
        //随机数
        $state = self::getState();
        //session 缓存state
        //该参数可用于防止csrf攻击（跨站请求伪造攻击），建议第三方带上该参数，可设置为简单的随机数加session进行校验
        session()->put(self::getOauthStateSessionKey(), $state);
        $redirectUri = self::getRedirectUri();
        //https://open.weixin.qq.com/connect/qrconnect?appid=APPID&redirect_uri=REDIRECT_URI&response_type=code&scope=SCOPE&state=STATE#wechat_redirect
        return self::WECHAT_URL . self::APP_ID . '&redirect_uri=' . $redirectUri . '&response_type=code&scope=snsapi_login&state=' . $state . '#wechat_redirect';
    }

    /**
     * 获取资源码(access_token)的url
     */
    public static function getAcessTokenUrl($code)
    {
        //https://api.weixin.qq.com/sns/oauth2/access_token?appid=APPID&secret=SECRET&code=CODE&grant_type=authorization_code
        return self::WECHAT_GET_ACCESS_TOKEN_URL . self::APP_ID . '&secret=' . self::APP_SECRET . '&code=' . $code . '&grant_type=authorization_code';
    }

    /**
     * 获取微信用户信息的url
     */
    public static function getWechatUserInfoUrl($accessToken)
    {
        return self::WECHAT_GET_USERINFO_URL.$accessToken.'&openid='.self::APP_ID;
    }

    public static function getOauthStateSessionKey()
    {
        return md5(self::OAUTH_STATE_KEY);
    }
}